extends EnemyBase

const JUMP_VELOCITY = -300.0  # 添加跳跃速度常量
const INVINCIBLE_TIME = 1.5  # 无敌时间持续1.5秒
const DAMAGE_COUNT_RESET_TIME = 2.0  # 重置伤害计数的时间
const DAMAGE_COUNT_THRESHOLD = 4  # 触发无敌状态的伤害次数
const PHASE_TWO_SPEED = 160  # 第二阶段的速度
const PHASE_TWO_THRESHOLD = 0.5  # 50%血量时进入第二阶段
const PHASE_TWO_ATTACK_COOLDOWN = 0.1  # 减少连续攻击之间的间隔
const PHASE_TWO_ATTACK_COUNT = 2  # 改为2次连续攻击
const PHASE_TWO_ANIMATION_SPEED = 1.5  # 正常动画速度
const PHASE_TWO_TELEPORT_CHANCE = 0.2  # 20%的概率触发闪现
const TELEPORT_DISTANCE = 40  # 闪现到玩家后方的距离
const TELEPORT_COOLDOWN = 3.0  # 闪现冷却时间
const TELEPORT_ATTACK_SPEED = 1.5  # 闪现攻击的动画速度（比正常稍快但不会太快）
const TELEPORT_ATTACK_RECOVERY = 0.8  # 闪现攻击后的恢复时间
const BATTLE_AREA_LEFT = 0  # 战斗区域左边界
const BATTLE_AREA_RIGHT = 400  # 战斗区域右边界
const ATTACK_COUNT_RESET_TIME = 2.0  # 2秒内的连续攻击计数重置时间
const MAX_CONTINUOUS_ATTACKS = 3  # 最大连续攻击次数
	
@onready var player_detection = $PlayerDetection
@onready var attack_range = $AttackRange
@onready var current_dialog: Control = null  # 添加对话框引用
var current_dialog_index = 0  # 添加当前对话索引

var player = null
var can_attack = true
var attack_cooldown = 0.5
var original_x = 0.0
var has_talked = false  # 新增:标记是否已经对话过
var is_invincible = false

# 添加伤害计数相关变量
var damage_count = 0
var damage_reset_timer = null  # 保持这个引用，但我们不需要手动清理它

var phase_two_triggered = false  # 是否已触发第二阶段
var original_speed = 0  # 保存原始速度

var current_attack_count = 0  # 当前攻击次数计数
var base_attack_cooldown = 0.5  # 保存基础攻击冷却时间

var can_teleport = true  # 是否可以闪现
var teleport_tween: Tween  # 用于闪现动画

# 添加一个变量来标记是否刚完成闪现攻击
var just_teleported = false

var dialog_data = [
	{ "name": "剑士", "text": "你是谁？为什么来到这里？" },
	{ "name": "玩家", "text": "我是一名旅行者，正在寻找变强的方法。" },
	{ "name": "剑士", "text": "很好...让我来测试一下你的实力！" }  # 这句话是剑士说的
]

var phase_two_dialog = [
	{ "name": "剑士", "text": "不错嘛，看来你确实有几分实力..." },
	{ "name": "剑士", "text": "那么接下来，就让你见识一下我真正的速度！" }
]

# 新增：防止第二阶段连续攻击时，玩家持续被伤害而卡在受伤动画
var last_hit_time = 0.0
const HIT_COOLDOWN = 0.5

signal dialog_started
signal dialog_ended
signal phase_two_dialog_started
signal phase_two_dialog_ended

var continuous_attack_count = 0  # 连续攻击计数
var attack_count_timer = null  # 计时器引用

func _ready() -> void:
	super._ready()
	add_to_group("sword_master")  # 添加到组以便玩家可以找到
	max_health = 100
	current_health = max_health    # 同步当前生命值
	move_speed = 100
	attack_damage = 20
	original_x = global_position.x
	original_speed = move_speed  # 保存原始速度
	
	# 初始时隐藏血条
	health_bar.hide()

	# 连接检测信号
	player_detection.body_entered.connect(_on_player_detected)
	player_detection.body_exited.connect(_on_player_lost)
	attack_range.body_entered.connect(_on_player_in_attack_range)

	animated_sprite.animation_finished.connect(_on_animation_finished)
	animated_sprite.play("idle")
	
	# 预加载对话气泡场景
	current_dialog = preload("res://scenes/bubble_dialog.tscn").instantiate()
	add_child(current_dialog)
	current_dialog.hide()
	current_dialog.dialog_finished.connect(_on_bubble_dialog_finished)

	base_attack_cooldown = attack_cooldown  # 保存基础攻击冷却时间

func _physics_process(delta):
	if is_dead:  # 如果已经死亡，直接返回
		return
		
	if not is_on_floor():
		velocity.y += ProjectSettings.get_setting("physics/2d/default_gravity") * delta
	
	# 检查玩家是否死亡
	if player and player.is_dead:
		velocity.x = 0
		animated_sprite.play("idle")
		return

	if is_hurt:
		velocity.x = 0
		return
		
	# 如果正在对话，保持静止并面向玩家
	if current_dialog and current_dialog.visible:
		velocity.x = 0
		if player:  # 确保在对话时面向玩家
			animated_sprite.flip_h = player.global_position.x < global_position.x
		animated_sprite.play("idle")
		move_and_slide()
		return

	match state:
		"chase":
			if player:
				var direction = (player.global_position - global_position).normalized()
				var distance = global_position.distance_to(player.global_position)
				var height_diff = abs(player.global_position.y - global_position.y)
				
				# 如果在二阶段且可以闪现，尝试触发闪现
				if phase_two_triggered and can_teleport and distance > 50:
					if randf() < PHASE_TWO_TELEPORT_CHANCE:
						perform_teleport_attack()
						return
				
				# 如果高度差太大，放弃追击
				if height_diff > 100:
					state = "idle"
					return
				
				# 只在非攻击状态且非连击状态下更新朝向
				if state != "attack" and (not phase_two_triggered or current_attack_count == 0):
					animated_sprite.flip_h = player.global_position.x < global_position.x
					attack_range.scale.x = -0.5 if animated_sprite.flip_h else 0.5
				
				# 检查是否在攻击范围内
				if distance <= 35:  # 攻击距离阈值
					velocity.x = 0
					if can_attack:
						state = "attack"
						perform_attack()
					else:
						animated_sprite.play("idle")  # 在攻击范围内等待时播放idle
				else:
					# 继续追击
					velocity.x = direction.x * move_speed
					animated_sprite.play("run")
		"attack":
			velocity.x = 0
			if not animated_sprite.animation == "attack":
				animated_sprite.play("attack")
		"idle":
			velocity.x = 0
			animated_sprite.play("idle")
	
	move_and_slide()

func perform_attack():
	if is_dead:  # 如果已经死亡，不能攻击
		return
		
	# 检查连续攻击次数
	continuous_attack_count += 1
	if continuous_attack_count >= MAX_CONTINUOUS_ATTACKS:
		can_attack = false
		state = "chase"
		# 创建冷却计时器
		await get_tree().create_timer(ATTACK_COUNT_RESET_TIME).timeout
		continuous_attack_count = 0  # 重置计数
		can_attack = true
		return
	
	# 重置之前的计时器（如果存在）
	if attack_count_timer and attack_count_timer.time_left > 0:
		attack_count_timer.timeout.disconnect(_reset_attack_count)
	
	# 创建新的计时器
	attack_count_timer = get_tree().create_timer(ATTACK_COUNT_RESET_TIME)
	attack_count_timer.timeout.connect(_reset_attack_count)
	
	# 正常的攻击逻辑
	can_attack = false
	animated_sprite.play("attack")
	# 在二阶段时才加快攻击动画的速度
	if phase_two_triggered:
		animated_sprite.speed_scale = PHASE_TWO_ANIMATION_SPEED
	state = "attack"  # 确保状态是attack
	velocity.x = 0  # 确保攻击时停止移动

func _on_player_detected(body):
	if body.is_in_group("player"):
		player = body
		# 立即更新朝向
		animated_sprite.flip_h = player.global_position.x < global_position.x
		
		# 只有在未对话过且当前没有对话在进行时才开始对话
		if not has_talked and (not current_dialog or not current_dialog.visible):
			current_dialog_index = 0
			show_next_dialog()
		elif has_talked and not is_dead:  # 如果已经对话过且没死，直接追击
			state = "chase"

func _on_player_lost(body):
	if body.is_in_group("player"):
		player = null
		state = "idle"

func _on_player_in_attack_range(body):
	if is_dead or not can_attack:  # 如果已经死亡或不能攻击，直接返回
		return
		
	if body.is_in_group("player") and (state == "chase" or state == "idle"):
		if phase_two_triggered or continuous_attack_count < MAX_CONTINUOUS_ATTACKS:
			state = "attack"
			perform_attack()
		
func _on_animation_finished():
	if animated_sprite.animation == "attack":
		# 攻击动画结束后恢复正常速度
		animated_sprite.speed_scale = 1.0
		
		if player and attack_range.overlaps_body(player):
			if phase_two_triggered:
				var current_time = Time.get_ticks_usec() / 1000.0
				# 只有超过冷却时间才能再次对玩家造成伤害
				if current_time - last_hit_time > HIT_COOLDOWN:
					player.take_damage(attack_damage, global_position)
					last_hit_time = current_time
					print("攻击命中")
			else:
				player.take_damage(attack_damage, global_position)
				print("攻击命中")
		
		# 如果刚完成闪现攻击，不进行连击
		if just_teleported:
			current_attack_count = 0
			can_attack = false
			state = "chase"
			
			# 创建冷却计时器
			var cooldown_timer = get_tree().create_timer(attack_cooldown)
			cooldown_timer.timeout.connect(func(): can_attack = true)
			return
		
		# 只允许非第二阶段时进行连击，第二阶段只挥一次刀
		if not phase_two_triggered and current_attack_count < PHASE_TWO_ATTACK_COUNT - 1:
			# 在第一阶段且还未完成连续攻击
			current_attack_count += 1

			# 根据连击次数增加等待时间
			var wait_time = 0.02  # 基础等待时间
			if current_attack_count == PHASE_TWO_ATTACK_COUNT - 1:
				wait_time = 0.5  # 最后一击前等待更长时间

			await get_tree().create_timer(wait_time).timeout
			can_attack = true
			perform_attack()
		else:
			# 所有攻击完成后才改变状态和重置计数
			current_attack_count = 0  # 重置攻击计数
			can_attack = false

			# 方案1：增大偏移距离，使剑士更远离玩家
			if phase_two_triggered and player:
				var offset = 40  # 偏移值增大到40像素
				if global_position.x < player.global_position.x:
					global_position.x -= offset
				else:
					global_position.x += offset

			# 方案2：临时禁用攻击碰撞检测，避免重复触发伤害
			attack_range.monitoring = false
			await get_tree().create_timer(0.5).timeout
			attack_range.monitoring = true

			state = "chase"  # 现在可以改变朝向了

			if phase_two_triggered:
				var cooldown_timer = get_tree().create_timer(attack_cooldown)
				cooldown_timer.timeout.connect(func(): can_attack = true)
			else:
				can_attack = true
	
	elif animated_sprite.animation == "hurt":
		is_hurt = false
		can_attack = true  # 重置攻击状态，允许再次攻击
		if player:
			state = "chase"

func show_next_dialog():
	if current_dialog_index < dialog_data.size():
		var message = dialog_data[current_dialog_index]
		if current_dialog_index == 0:  # 对话开始
			print("发送对话开始信号")  # 调试信息
			if not phase_two_triggered:  # 只在第一阶段对话时限制玩家移动
				emit_signal("dialog_started")
			is_invincible = true  # 进入无敌状态
			if health_bar:
				health_bar.hide()  # 隐藏血条
		current_dialog.show_dialog(message.get("text"), 2.0)
		current_dialog_index += 1

func _on_bubble_dialog_finished():
	if current_dialog_index < dialog_data.size():
		show_next_dialog()
	else:
		current_dialog_index = 0
		has_talked = true
		if not phase_two_triggered:  # 只在第一阶段对话时发送对话结束信号
			emit_signal("dialog_ended")
		is_invincible = false  # 对话结束，退出无敌状态
		if health_bar:
			health_bar.show()  # 显示血条
		if player:
			state = "chase"

func _process(_delta):
	if is_dead:
		return
		
	if current_dialog and current_dialog.visible:
		# 确保 current_dialog_index 在有效范围内
		if current_dialog_index > 0 and current_dialog_index <= dialog_data.size():
			# 获取当前正在显示的对话
			var current_message = dialog_data[current_dialog_index - 1]
			if current_message.get("name") == "玩家":
				# 玩家的对话显示在玩家头顶
				if player:
					current_dialog.update_position(player.global_position, true)
			else:  # 剑士的对话显示在剑士头顶
				current_dialog.update_position(global_position)

func take_damage(amount: float, source_position: Vector2 = Vector2.ZERO, is_quick_slash: bool = false) -> void:
	if is_dead or is_invincible:
		return
		
	# 只在非对话状态下显示血条
	if health_bar and (not current_dialog or not current_dialog.visible):
		health_bar.show()
	
	# 不直接调用父类方法，因为我们有自定义的生命值处理逻辑
	current_health -= amount
	current_health = max(0, current_health)
	
	# 检查是否生命值为0
	var is_fatal_hit = current_health <= 0
	
	# 更新血条 - 使用自定义方法
	if health_bar:
		if is_fatal_hit:
			# 如果是致命一击，直接清空血条
			health_bar.clear_health_bar()
		else:
			# 否则正常更新血条
			health_bar.set_health(current_health, max_health)
	
	# 检查是否触发第二阶段
	if not phase_two_triggered and current_health <= max_health * PHASE_TWO_THRESHOLD:
		phase_two_triggered = true
		enter_phase_two()
	
	print("敌人受到伤害：", amount, " 当前生命值：", current_health)
	
	# 疾风斩造成的伤害特殊处理
	if is_quick_slash:
		# 添加特殊视觉效果而不打断当前状态
		var tween = create_tween()
		tween.tween_property(animated_sprite, "modulate", Color(2.0, 1.5, 1.5, 0.7), 0.1)
		tween.tween_property(animated_sprite, "modulate", Color(1, 1, 1, 1), 0.1)
		return
	
	# 增加伤害计数
	damage_count += 1
	
	# 重置之前的计时器（如果存在）
	if damage_reset_timer and damage_reset_timer.time_left > 0:
		damage_reset_timer.timeout.disconnect(_reset_damage_count)
	
	# 创建新的计时器
	damage_reset_timer = get_tree().create_timer(DAMAGE_COUNT_RESET_TIME)
	damage_reset_timer.timeout.connect(_reset_damage_count)
	
	if is_fatal_hit:
		die()
	else:
		is_hurt = true
		animated_sprite.play("hurt")
		
		# 如果达到伤害阈值，进入无敌状态
		if damage_count >= DAMAGE_COUNT_THRESHOLD:
			is_invincible = true
			print("连续受伤", DAMAGE_COUNT_THRESHOLD, "次，进入无敌状态")
			
			# 创建闪烁效果
			var tween = create_tween()
			for i in range(4):
				tween.tween_property(animated_sprite, "modulate:a", 0.2, 0.2)
				tween.tween_property(animated_sprite, "modulate:a", 1.0, 0.2)
			
			# 等待无敌时间结束
			await get_tree().create_timer(INVINCIBLE_TIME).timeout
			is_invincible = false
			damage_count = 0  # 重置伤害计数
		
		# 等待受伤动画结束
		await animated_sprite.animation_finished
		is_hurt = false

func _reset_damage_count():
	if not is_invincible:  # 只在非无敌状态下重置计数
		damage_count = 0
		print("重置伤害计数")

func enter_phase_two():
	# 进入无敌状态
	is_invincible = true
	state = "idle"
	velocity = Vector2.ZERO
	animated_sprite.play("idle")  # 播放idle动画
	if health_bar:
		health_bar.hide()  # 隐藏血条
	
	# 发送第二阶段对话开始信号
	emit_signal("phase_two_dialog_started")
	
	# 显示第二阶段对话
	current_dialog_index = 0
	dialog_data = phase_two_dialog
	show_next_dialog()
	
	# 等待对话完成
	await current_dialog.dialog_finished
	await get_tree().create_timer(1.0).timeout  # 给一点额外时间让对话完全结束
	
	# 等待对话框完全隐藏
	await get_tree().create_timer(0.5).timeout  # 等待对话框淡出动画
	
	# 增加速度和减少攻击冷却时间
	move_speed = PHASE_TWO_SPEED
	attack_cooldown = PHASE_TWO_ATTACK_COOLDOWN
	
	# 添加一些视觉效果
	var tween = create_tween()
	tween.tween_property(animated_sprite, "modulate", Color(1.2, 1.0, 1.0), 0.5)
	
	# 等待视觉效果完成后再恢复追击
	await tween.finished
	
	# 等待2秒再开始追击
	await get_tree().create_timer(2.0).timeout
	
	# 退出无敌状态并恢复追击
	is_invincible = false
	if health_bar:
		health_bar.show()
	
	# 发送第二阶段对话结束信号
	emit_signal("phase_two_dialog_ended")
	
	if player:
		state = "chase"
		can_attack = true  # 确保可以攻击
		animated_sprite.flip_h = player.global_position.x < global_position.x

func perform_teleport_attack():
	can_teleport = false
	state = "teleport"
	just_teleported = true  # 设置标记
	
	# 创建闪现效果
	modulate.a = 0.5
	
	# 计算目标位置（玩家身后）
	var target_pos = player.global_position
	target_pos.x += TELEPORT_DISTANCE * (-1 if player.animated_sprite.flip_h else 1)
	
	# 限制在战斗区域内
	target_pos.x = clamp(target_pos.x, BATTLE_AREA_LEFT, BATTLE_AREA_RIGHT)
	
	# 保持在地面上
	target_pos.y = global_position.y
	
	# 检查目标位置是否有效
	if abs(target_pos.x - global_position.x) < 20:  # 如果目标位置太近
		can_teleport = true  # 重置闪现状态
		state = "chase"  # 恢复追击状态
		modulate.a = 1.0  # 恢复透明度
		return
	
	# 创建闪现动画
	teleport_tween = create_tween()
	teleport_tween.tween_property(self, "modulate:a", 0.0, 0.1)
	teleport_tween.tween_callback(func():
		# 瞬移到目标位置
		global_position = target_pos
		# 确保面向玩家
		animated_sprite.flip_h = player.global_position.x < global_position.x
		attack_range.scale.x = -0.5 if animated_sprite.flip_h else 0.5
	)
	teleport_tween.tween_property(self, "modulate:a", 1.0, 0.1)
	teleport_tween.tween_callback(func():
		# 立即发动攻击，但不改变动画速度
		state = "attack"
		animated_sprite.play("attack")  # 直接播放攻击动画，不通过 perform_attack()
		
		# 等待攻击动画完成
		await animated_sprite.animation_finished
		
		# 攻击完成后直接恢复追击
		state = "chase"
		
		# 设置闪现冷却
		get_tree().create_timer(TELEPORT_COOLDOWN).timeout.connect(func(): 
			can_teleport = true
			just_teleported = false  # 重置标记
		)
	)

func _reset_attack_count():
	continuous_attack_count = 0
	print("重置连续攻击计数")

func die() -> void:
	if is_dead:
		return
		
	is_dead = true
	velocity = Vector2.ZERO
	
	# 停止所有正在进行的对话
	if current_dialog and current_dialog.visible:
		current_dialog.hide()
	
	# 确保血条立即更新为空
	if health_bar:
		# 先设置生命值为0
		current_health = 0
		# 使用专门的方法清空血条
		health_bar.clear_health_bar()
	
	# 给玩家增加经验值
	if player and player.stats:
		var exp_reward = 200  # 剑术大师给予的经验值奖励
		player.stats.add_exp(exp_reward)
		print("玩家获得经验值：", exp_reward)
	
	# 播放idle动画而不是death动画
	animated_sprite.play("idle")
	
	# 禁用碰撞
	$CollisionShape2D.set_deferred("disabled", true)
	
	# 禁用所有检测区域
	player_detection.monitoring = false
	attack_range.monitoring = false
	
	print("剑术大师死亡，准备闪烁并消失")
	
	# 使用安全的方式等待动画完成
	if animated_sprite.is_connected("animation_finished", _on_animation_finished):
		animated_sprite.animation_finished.disconnect(_on_animation_finished)
	
	# 创建闪烁效果
	var tween = create_tween()
	for i in range(5):  # 闪烁5次
		tween.tween_property(animated_sprite, "modulate:a", 0.2, 0.2)
		tween.tween_property(animated_sprite, "modulate:a", 1.0, 0.2)
	
	# 等待闪烁完成后淡出
	tween.tween_callback(func():
		var fade_out = create_tween()
		fade_out.tween_property(animated_sprite, "modulate:a", 0.0, 1.0)
		fade_out.tween_callback(func():
			print("剑术大师被移除")
			queue_free()
		)
	)
